<script setup>
import {onBeforeUnmount, onMounted, reactive, ref} from "vue"
import {Search} from "@element-plus/icons-vue";
import productItemVue from "@/views/productItem.vue"
import {getGoodsService, getGuessYouLikeService, getHotTopGoodsService, getRecommendGoodsService} from "@/api/goods.js";
import {useRouter} from 'vue-router'
import {getHotSearchService} from "@/api/HotSearch.js";
import {useTokenStore} from "@/stores/token.js";
import {getUserInfoService} from "@/api/user.js";
import {ElMessage} from "element-plus";
import {useUserIdStore} from "@/stores/userInfo.js";
import {useDefaultAvatarStore} from "@/stores/defaultAvatar.js";
import {getTotalNoticeNumService} from "@/api/messages.js";
import {saveUserBehaviorService} from "@/api/userBehavior.js";


const route = useRouter()
const title = ref('')

//搜索框关键字
const searchInput = ref("")
const showUserMessage = ref(false)
const totalNoticeNum = ref(0); // 当前用户总共未读消息数量 在首页展示
const recommendGoodsList = ref([]) //推荐商品列表
const hotTopGoodsList = ref([]) // 热门商品列表
const guessYouLikeGoodsList = ref([])

const tokenStore = useTokenStore()

// 用户行为
const userBehavior = reactive({
  behaviorType:null,
  searchKeyword:null
});


const getGuessLikeGoods = async () => {
  if (tokenStore.token === ''){
    return;
  }
  let res = await getGuessYouLikeService();
  guessYouLikeGoodsList.value = res.data;
}
getGuessLikeGoods();

const getTotalNoticeNum = async () => {
  if (tokenStore.token === ''){
    return;
  }
  let result = await getTotalNoticeNumService();
  totalNoticeNum.value = result.data;
}
getTotalNoticeNum();

const intervalId2 = setInterval(async () => {
  await getTotalNoticeNum();
}, 10000);

onMounted(()=>{
  title.value = route.currentRoute.value.meta.title;
  document.title = title.value;

  getHotTopGoods();
  getRecommendGoods();
})

const getHotTopGoods = async () => {
  let result = await getHotTopGoodsService();
  hotTopGoodsList.value = result.data;
}



const keyupEvent = (event) => {
  if (event.key === "Enter") {
    event.preventDefault();
    event.stopPropagation();
    console.log('Enter键被按下');
    buttonSearch();
  }
}
window.addEventListener('keyup', keyupEvent)

onBeforeUnmount(() => {
  window.removeEventListener('keyup', keyupEvent);
  clearInterval(intervalId);
  clearInterval(intervalId2);
})

// 热搜
const HotSearchStatus = ref(false)
// 热搜展示数据
const hotSearchData = ref([])

const getHotSearchData = async () => {
  let result = await getHotSearchService();
  hotSearchData.value = result.data
}
const openHotSearch = () => {
  HotSearchStatus.value = true;
  getHotSearchData()
}

const closeHotSearch = () => {
  HotSearchStatus.value = false;
}


const hotRowItemClicked = (item) => {
  searchInput.value = item
  HotSearchStatus.value = false;
  // route.push({path:'/layout',query:{search:searchInput.value}});
}
const token = useTokenStore()

const goHomePage = () => {
  HotSearchStatus.value = false;
  route.push('/')
}

const userAvatar = ref('')
const defaultAvatarStore = useDefaultAvatarStore();
//默认头像
const defaultPic = ref(defaultAvatarStore.defaultAvatar)
const getUserAvatar = async () => {
  let result = await getUserInfoService();
  userAvatar.value = result.data.userPic === "" || result.data.userPic === null ? defaultPic.value : result.data.userPic;
}
getUserAvatar();

const showMessage = () => {
  showUserMessage.value = true;
}


const closeMessage = () => {
  showUserMessage.value = false;
}

const buttonSearch = ()=>{
  if (searchInput.value === ''){
    return;
  }
  userBehavior.behaviorType = 1;
  userBehavior.searchKeyword = searchInput.value;
  saveUserBehaviorService(userBehavior);
  route.push({path:'/layout',query:{search:searchInput.value}});
}


const flag = ref(false) //控制消息中心字体闪烁
const intervalId =setInterval(()=>{
  flag.value = !flag.value;
},300)

const userIdStore = useUserIdStore();
//退出登录
const logout = () => {
  token.removeToken();
  userIdStore.removeUserId();
  showUserMessage.value = false;
  location.reload(); //刷新页面
  ElMessage.success('退出成功')
}
const openHtml = (url)=>{
  window.open(url,'_self')
}

//获取每日推荐商品
const getRecommendGoods = async()=>{
  let result = await getRecommendGoodsService();
  recommendGoodsList.value = result.data;
}

const changeBatch = ()=>{
  getGuessLikeGoods();
}

</script>

<template>
  <el-container class="layout-container">
    <el-header class="layout-header" @click.self="closeHotSearch">
      <!--  <p>校林二手交易圈</p>-->
      <img class="logo" src="../assets/logo1.png" alt="logo" @click="goHomePage"/>
      <div class="left-title-nav">
        <el-link href="/">首页</el-link>
        <el-link href="/">分类</el-link>
      </div>
      <div class="search-input">
        <el-input class="search"
                  v-model="searchInput"
                  placeholder="搜索一下"
                  @focus="openHotSearch"
                  :prefix-icon="Search"/>
        <el-button type="primary" class="search-button" @click="buttonSearch" @focus="closeHotSearch">搜索</el-button>
        <div class="title-nav">
          <el-link href="/layout">所有商品</el-link>
          <el-link href="/requiredGoods">求购广场</el-link>
          <el-link href="/AITalk">校林AI助手</el-link>
        </div>
      </div>
      <div v-show="HotSearchStatus" class="hot-search">
        <p>热门搜索</p>
        <el-row
            v-for="item in hotSearchData"
            :key="item"
            class="hot-row"
            @click="hotRowItemClicked(item)">
          <span>{{ item }}</span>
        </el-row>
      </div>
      <div class="login-div">
        <el-link v-if="token.token === null || token.token.length === 0" class="login" href="/login"><p>登录</p>
        </el-link>
        <div v-else class="avatar-info" @mouseover="showMessage" @mouseleave="closeMessage">
          <div style="height: 100%;display: flex;align-items: center;position: relative">
            <img :src="userAvatar" alt="avatar" style="border-radius: 50%;background-size: cover;width: 40px;height: 40px;">
            <p v-if="totalNoticeNum!==0" class="total-notice">{{totalNoticeNum}}</p>
          </div>
          <div v-if="showUserMessage" class="user-message" @mouseleave="closeMessage">
            <div class="user-message-item" @click="route.push('/pushRequiredGoods')"><p style="font-weight: bold">发布求购</p></div>
            <div class="user-message-item" @click="route.push('/pushGoods')"><p style="font-weight: bold">发布商品</p>
            </div>
            <div class="user-message-item" @click="route.push('/myPushCenter')"><p style="font-weight: bold">我的发布</p></div>
            <div class="user-message-item" @click="route.push('/messageCenter')">
              <p style="font-weight: bold;" :style="totalNoticeNum!==0&&flag ? {color: 'red'} : {}">消息中心</p>
            </div>
            <div class="user-message-item" @click="route.push('/personalCenter')"><p style="font-weight: bold">
              个人中心</p></div>
            <div class="user-message-item" @click="logout"><p style="font-weight: bold">退出登录</p></div>
          </div>
        </div>
      </div>
    </el-header>
    <el-main
        class="layout-main"
        @click="closeHotSearch">
      <div class="banner">
        <el-carousel height="400px" motion-blur style="border-radius: 10px;box-shadow: 0 0 10px rgba(0,0,0,.2)">
          <el-carousel-item v-for="item in 2" :key="item">
            <img style="width: 100%;height: 100%;background-size: contain" src="@/assets/banner2.png" alt="banner">
          </el-carousel-item>
        </el-carousel>
      </div>
      <div class="recommend-item">
        <p style="font-size: 20px;font-weight: bold;border-top: none;margin: 0 0 0 20px;display: flex;justify-content: space-between;color: rgb(44,36,36);">每日优选 :</p>
        <div class="items-main-content">
          <product-item-vue
              class="product-item"
              v-for="item in recommendGoodsList"
              :key="item.id"
              :goods="item"
          >
          </product-item-vue>
        </div>
      </div>
      <div class="hot-item">
        <p style="font-size: 20px;font-weight: bold;border-top: none;margin: 0 0 0 20px;display: flex;justify-content: space-between;color: rgb(44,36,36);">热门TOP :</p>
        <div class="items-main-content">
          <product-item-vue
              class="product-item"
              v-for="item in hotTopGoodsList"
              :key="item.id"
              :goods="item"
          >
          </product-item-vue>
      </div>
      </div>
      <div v-if="tokenStore.token !== ''" class="guess-you-like-item">
        <div style="display: flex;justify-content: space-between;">
          <p style="font-size: 20px;font-weight: bold;border-top: none;margin: 0 0 0 20px;display: flex;justify-content: space-between;color: rgb(44,36,36);">猜你喜欢 :</p>
          <p class="change-batch" @click="changeBatch()">换一批</p>
        </div>
        <div class="items-main-content">
          <product-item-vue
              class="product-item"
              v-for="item in guessYouLikeGoodsList"
              :key="item.id"
              :goods="item"
          >
          </product-item-vue>
        </div>
      </div>
      <div class="footer">
        <div class="footer-top">
          <div class="footer-msg">
            <p @click="openHtml('/public/aboutUs.html')">关于我们&nbsp;</p>
            <p @click="openHtml('/public/privacyPolicy.html')">隐私政策&nbsp;</p>
            <p>商务合作&nbsp;</p>
          </div>
        </div>
        <div class="footer-bottom">
          <div class="web-base-info">
            <p>@2024 · 校林二手交易圈 · ALL RIGHTS RESERVED · 皖ICP备00000000000号</p>
            <p>安徽省合肥市合肥师范学院</p>
          </div>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<style lang="scss" scoped>
.layout-container {
  .layout-header {
    background-color: #e8e8e8;
    height: 55px;
    display: flex;
    flex-direction: row;
    align-items: center;
    position: relative;
    transition: all 0.3s ease-in-out;

    img {
      height: 70%;

      &:hover {
        cursor: pointer;
      }
    }

    .search-input {
      height: 100%;
      width: auto;
      display: flex;
      position: absolute;
      left: 35%;
      top: 15%;
    }

    .search {
      height: 70%;
      width: 350px;
      border-radius: 1px;
    }

    .hot-search {
      position: absolute;
      left: 35%;
      top: 85%;
      z-index: 1000;
      width: 349px;
      min-height: 50px;
      background-color: #fdfdfd;
      box-shadow: 0 5px 10px rgba(0, 0, 0, 0.4);
      border-radius: 0 0 10px 10px;

      p {
        margin: 10px;
        font-size: 15px;
        font-weight: bold;
        color: #000000;
      }

      .hot-row {
        width: 100%;
        height: auto;

        span {
          width: 100%;
          padding: 5px 0;
          margin-left: 10px;
          font-size: 15px;
          color: #545454;
          white-space: nowrap;
          overflow:hidden;
          text-overflow: ellipsis;
        }

        &:hover {
          background-color: #d2d0d0;
          cursor: pointer;
        }
      }
    }

    .search-button {
      //margin-left: 20px;
      //position: absolute;
      //right: 38%;
      margin-left: 10px;
      margin-top: 1px;
      height: 65%;
      width: 90px;
      background-color: #f66002;
      border: 1px solid #f66002;

      &:hover {
        background-color: rgb(255, 0, 0);
      }
    }

    .login-div {
      height: 100%;
      width: 70px;
      position: absolute;
      right: 25px;
      display: flex;
      align-items: center;

      img {
        height: 60%;
        width: 60%;
      }
    }

    .login {
      height: 100%;
      width: 100%;
      font-size: 18px;
      text-decoration: none;

      p {
        font-weight: bold;
      }

      &:hover {
        cursor: pointer;
        background-color: white;
        border-radius: 3px;
        color: #f66002;
        transition: all 0.3s ease-in-out;
      }
    }

    .left-title-nav {
      width: 160px;
      height: 100%;

      .el-link {
        width: 80px;
      }
    }

    .title-nav {
      height: 100%;
      margin-left: 60px;
      margin-top: -9px;
      display: flex;
      justify-content: space-between;
    }

    .el-link {
      height: 100%;
      width: 100px;
      font-size: 15px;
      text-decoration: none;
      &:hover {
        cursor: pointer;
        background-color: white;
        border-radius: 3px;
        color: #f66002;
        transition: all 0.3s ease-in-out;
      }
    }
  }

  .avatar-info {
    .total-notice{
      position: absolute;
      color: #fff;
      margin: 0;
      background-color: #ff0000;
      border-radius: 50%;
      width: 19px;
      height: 19px;
      text-align: center;
      line-height: 19px;
      font-size: 10px;
      top: -5px;
      right: -5px;
    }
  }

  .user-message {
    width: 100px;
    height: auto;
    background-color: white;
    border-radius: 10px;
    position: absolute;
    right: 0;
    top: 48px;
    z-index: 1000;

    .user-message-item {
      width: 100%;
      height: 20px;
      text-align: center;
      padding: 5px 0;
      cursor: pointer;

      p {
        font-size: 15px;
        font-weight: bold;
        margin: 0;
      }

      &:hover {
        background-color: #f66002;
        border-radius: 10px;
        color: white;
      }
    }
  }

  .layout-main {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 0;
    .banner{
      margin-top: 25px;
      width: 90%;
    }
    .recommend-item{
      width: 88%;
      margin-top: 25px;
      background-color: #f5f1f1;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.4);
      border-radius: 10px;
      padding: 0 10px 20px 10px;
    }
    .hot-item{
      width: 88%;
      margin-top: 60px;
      background-color: #f5f1f1;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.4);
      border-radius: 10px;
      padding: 0 10px 20px 10px;
    }
    .guess-you-like-item{
      width: 88%;
      margin-top: 60px;
      background-color: #f5f1f1;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.4);
      border-radius: 10px;
      padding: 0 10px 20px 10px;
      .change-batch{
        font-size: 16px;
        border-top: none;
        margin: 0 20px 0 0;
        display: flex;
        color: rgb(44,36,36);
        user-select: none;
        &:hover{
          color: #f6024b;
          transition: all 0.3s ease-in-out;
          cursor: pointer;
        }
      }
    }
    .items-main-content{
      margin-left: 1%;
      width: 100%;
      display: grid;
      padding: 10px 20px;
      grid-template-columns: repeat(4, 1fr);
      grid-row-gap: 20px;
      grid-column-gap: 1%;
    }
    .footer{
      margin-top: 25px;
      width: 100%;
      height: 100px;
      background-color: #464646;
      display: flex;
      flex-direction: column;
      align-items: center;
      .footer-top{
        width: 95%;
        height: 50px;
        border-bottom: 1px solid #999;
        display: flex;
        justify-content: center;
        align-items: center;
        .footer-msg{
          height: 25px;
          display: flex;
          //margin-left: -20px;
          p{
            margin: 0 10px;
            font-size: 14px;
            padding: 0;
            border-top: none;
            color: #b7b7b7;
            line-height: 25px;
            &:hover{
              color: #f66002;
              transition: all 0.3s ease-in-out;
              cursor: pointer;
            }
          }
        }
      }
      .footer-bottom{
        width: 90%;
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        .web-base-info{
          width: 70%;
          height: 30px;
          display: flex;
          justify-content: center;
          p{
            margin: 0 10px;
            font-size: 14px;
            padding: 0;
            border-top: none;
            color: #b7b7b7;
            line-height: 30px;
            &:hover{
              color: #f66002;
              transition: all 0.3s ease-in-out;
              cursor: pointer;
            }
          }
        }
      }
    }
    .grid-container {
      width: 76%;
      display: grid;
      grid-template-columns: repeat(4, 1fr); // 创建四列布局
      margin: 0 auto;

      .product-item {
        margin-bottom: 15px;
      }
    }

    .data-loading {
      margin-top: 10px;
      text-align: center;
    }

    p {
      border-top: 1px solid #999;
      text-align: center;
      color: #999;
      font-size: 20px;
      padding: 20px 0;
    }
  }
}

// 新增隐藏头部样式
.header-hidden {
  transform: translateY(-100%);
  opacity: 0;
}
</style>